package com.uw.uwconfig.client.repository;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

public class ConfigCacheHolder {
    private static final Map<String, Map<String, Object>> configHolder = new HashMap<>();

    public synchronized static Map<String, Object> getConfig(String key) {
        return configHolder.get(key);
    }

    public synchronized static void putConfig(String key, Map<String, Object> configs) {
        configHolder.put(key, configs);
    }


    public static Map<String, Object> compare(Map<String, Object> oldConfig, Map<String, Object> newConfig) {
        if (CollectionUtils.isEmpty(oldConfig)) {
            return newConfig;
        }
        if (CollectionUtils.isEmpty(newConfig)) {
            return oldConfig;
        }

        Map<String, Object> result = new HashMap<>();
        // 处理 newConfig 新增值和更新值
        newConfig.forEach((k,v) -> {
            if (!v.equals(oldConfig.get(k))) {
                result.put(k, v);
            }
        });

        // 处理 newConfig 移除值。
        oldConfig.forEach((k,v) -> {
            if (!newConfig.containsKey(k)) {
                result.put(k, v);
            }
        });

        return result;
    }

}
